//
//  SLMP4Parser+Root.m
//  SLVideoParser
//
//  Created by S_LINE on 2020/6/19.
//  Copyright © 2020 S_LINE. All rights reserved.
//

#import "SLMP4Parser+Root.h"

#import "SLParserUtil.h"

@implementation SLMP4Parser (Root)

- (NSDictionary *)ftypParser:(NSData *)data
{
    NSMutableDictionary *dict = [NSMutableDictionary new];
    
    uint64_t length = 4;
    uint64_t count = data.length / length;
    NSString *versionKey = @"minorVersion";
    NSString *majorBrandKey = @"majorBrand";
    NSString *arrayKey = @"compatibleBrands";
    for (int i = 0; i < count; i++)
    {
        NSRange range = NSMakeRange(i * length, length);
        NSData *subData = [data subdataWithRange:range];
        if (i == 1)
        {
            uint64_t size = [SLParserUtil hexToDecimalWithData:subData];
            [dict setObject:[NSNumber numberWithUnsignedLongLong:size] forKey:versionKey];
        }
        else
        {
            NSString *type = [SLParserUtil hexToStringTypeWithData:subData];
            if (type) {
                if (i == 0)
                {
                    [dict setObject:type forKey:majorBrandKey];
                }
                else
                {
                    NSMutableArray *array = [NSMutableArray new];
                    if ([[dict allKeys] containsObject:arrayKey] && [[dict objectForKey:arrayKey] isKindOfClass:[NSArray class]])
                    {
                        array = [[dict objectForKey:arrayKey] mutableCopy];
                    }
                    [array addObject:type];
                    [dict setObject:[array copy] forKey:arrayKey];
                }
            }
        }
    }
    
    return [dict copy];
}

@end
